package icasue.base.utils.script;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/2/20 下午2:23
 * @UpdateDate:
 * @Description:
 */
public class SOKclient {
    public static void main(String[] args) {
        //客户端创建一个Socket通讯管道，用于跟Socket服务端进行通讯，host，port为Socket服务端的Identity.
        Socket socket = null;
        try {
            socket = new Socket("localhost",4477);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            if(socket != null){
                //客户端请求数据，服务端相应数据.
                String clientQue = null;
                String serverAns = null;
                //服务端应答数据读取流.
                BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //客户端请求数据输出流.
                PrintWriter clientWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                //模拟客户端请求数据的方式，控制台输入
                BufferedReader clientDataIn = new BufferedReader(new InputStreamReader(System.in, Charset.forName("utf-8")));
                while (socket != null && socket.isConnected()){
                    //以线程阻塞的方式获取客户端控制台输入，作为Socket交互的输入数据
                    clientQue = clientDataIn.readLine();

                    //把请求数据推入Socket通道的输出流.
                    clientWriter.println(clientQue);
                    clientWriter.flush();
                    if(clientQue.equalsIgnoreCase("BYE")){break;}

                    //以线程阻塞的方式获取来自客户端的应答.
                    serverAns = serverReader.readLine();
                    System.out.println(String.format("CLIENT_QUE: %s,    SERVER_ANS: %s",clientQue,serverAns));
                    if(serverAns.equalsIgnoreCase("BYE")){break;}
                }
                if(serverReader != null){serverReader.close();}
                if(clientWriter != null){clientWriter.close();}
                if(socket != null){ socket.close(); }
            }
        }catch (Throwable e){
            e.printStackTrace();
        }

    }
}
